package com.blog.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.blog.pojo.Article;
import com.blog.pojo.News;
import com.blog.pojo.RawNews;
import com.blog.pojo.SimpleNews;
import com.blog.service.NewsSpiderService;
import com.blog.service.RawNewsService;
import com.blog.service.impl.NewsSpiderServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;



@RestController
public class NewsSpiderController {

    // 爬取的新闻相关操作    完成
    // 提交到后台保存  完成，但是待完善
    // 单条修改，审核决定是否保存
    //  一键全部保存

    @Resource
    private NewsSpiderService newsSpiderService;

    @Autowired
    private RawNewsService rawNewsService;

    /**
     * 发布单条新闻
     * @RequestBody 将前台传来的json数据映射到对象中
     */
    @PostMapping("news/publish")
    public String publishNews(@RequestBody SimpleNews news, Model model){

        String Result = newsSpiderService.publishNews(news);
        model.addAttribute("isPublised",Result);
        return Result;
    }



    /**
     * 爬取新闻，同时保存
     */
    //date时间有问题 修正
    @GetMapping("/news/getRawItems")
    public String getRowItems(){
        // 获取所有的新闻SimpleNews
        String content = HttpUtil.get("https://ruanyf.github.io/sina-news/rss.json");
        News news = JSONUtil.toBean(content,News.class);
        List<SimpleNews> listnews = news.getItems();

        //处理成RawNews，保存到数据库中
        for (int i = 0; i < listnews.size(); i++) {
            RawNews rawNews = new RawNews(); //存到数据库的是RawNews

            SimpleNews temp = listnews.get(i);
            //System.out.println(temp);

            rawNews.setId(Integer.valueOf(temp.getId()));
            rawNews.setTitle(temp.getTitle());
            rawNews.setUrl(temp.getUrl());


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            StringBuilder sb = null;
            if(temp.getDate_modified() == null){
                sb.append(sdf.format(new Date()));
            }else{

                sb = new StringBuilder().append(temp.getDate_modified().substring(0,9)).append(" ").append(temp.getDate_modified().substring(11,19));
            }

            Date date1 = null;
            try {
                date1 = sdf.parse(sb.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            rawNews.setDate(date1);
            rawNews.setIsused(0);//默认存入数据库时，所有爬取的新闻都没有发表过
            rawNewsService.insert(rawNews);
        }
        return "爬取完成";
    }

    /**
     * 发表所有没发表过的新闻
     * @return
     */
      @GetMapping("/news/publishAllRawNews")
        public String publishAllRawNews(Model model){
          List<RawNews> unusedNews = rawNewsService.getUnusedNews();

          for (int i = 0; i <unusedNews.size() ; i++) {

              SimpleNews simpleNews = rawTosimple(unusedNews.get(i));
                //发表
              this.publishNews(simpleNews,model);
              //修改为发表过
              setNewsUsed(unusedNews.get(i).getId());
          }
          return "发布所有新闻成功";
      }

      public boolean setNewsUsed(int id){

          Boolean setUsed = rawNewsService.setRawNewsUsed(id);
          if (setUsed) {
              return true;
          }
         return false;

      }


      private SimpleNews rawTosimple(RawNews rawNews){

          SimpleNews simpleNews = new SimpleNews();

          simpleNews.setId(String.valueOf(rawNews.getId()));
          simpleNews.setContent_html(null);
          simpleNews.setUrl(rawNews.getUrl());
          simpleNews.setTitle(rawNews.getTitle());
          simpleNews.setDate_modified(rawNews.getDate().toString());

          return simpleNews;

      }



}
